#include <graphics.h>
#include <conio.h>
#include <time.h>

#define BallNum 10																//小球数量

void main()
{
	int ball_vx[BallNum], ball_vy[BallNum];										//小球运动速度
	int ball_x[BallNum], ball_y[BallNum];										//小球坐标
	int dx, dy;																	//两小球圆心坐标距离		
	int i, j;
	for (i = 0; i < BallNum; i++)
	{
		ball_vx[i] = 1;
		ball_vy[i] = 1;
	}
	initgraph(640, 480);
	srand(time(0));
	for (i = 0; i < BallNum; i++)
	{
		ball_x[i] = 10+rand()%600;
		ball_y[i] = 10+rand()%400;
	}								

	for (i = 0; i < BallNum - 1; i++)
		for (j = i + 1; j < BallNum; j++)
		{
			dx = (ball_x[i] - ball_x[j])*(ball_x[i] - ball_x[j]);
			dy = (ball_y[i] - ball_y[j])*(ball_y[i] - ball_y[j]);
			if ((dx + dy) <= 3600)
			{
				ball_x[i] = 1000;
				ball_y[i] = 1000;
			}
		}																		//小球坐标赋值
	BeginBatchDraw();
	while(1)
	{
		setcolor(YELLOW);
		setfillcolor(GREEN);
		for(i=0;i<BallNum;i++)
			fillcircle(ball_x[i], ball_y[i], 30);

		Sleep(3);

		FlushBatchDraw();

		setcolor(BLACK);
		setfillcolor(BLACK);
		for (i = 0; i < BallNum; i++)
			fillcircle(ball_x[i], ball_y[i], 30);								//打印小球

		for (i = 0; i < BallNum; i++)
		{
			ball_x[i] = ball_x[i] + ball_vx[i];
			ball_y[i] = ball_y[i] + ball_vy[i];
		}																		//小球移动

		for (i = 0; i < BallNum-1; i++)
			for (j = i+1; j < BallNum; j++)
			{
				dx = (ball_x[i] - ball_x[j])*(ball_x[i] - ball_x[j]);
				dy = (ball_y[i] - ball_y[j])*(ball_y[i] - ball_y[j]);
				if ((dx + dy) <= 3600)
				{
					ball_vx[i] = -ball_vx[i];
					ball_vy[i] = -ball_vy[i];
					ball_vx[j] = -ball_vx[j];
					ball_vy[j] = -ball_vy[j];
				}
			}								
		for (i = 0; i < BallNum; i++)
		{
			if (ball_x[i] == 620 || ball_x[i] == 20)
				ball_vx[i] = -ball_vx[i];
			if (ball_y[i] == 460 || ball_y[i] == 20)
				ball_vy[i] = -ball_vy[i];
		}																		//小球反弹
	}
	EndBatchDraw();
	getch();
	closegraph();
}
